# -*- coding:utf-8 -*-
# @ Script: 棍棍英雄辅助.py
# @ Author: Glory
# @ Email: 
# @ Create At: 2018-12-19 14:25:18
# @ Last Modified By: Glory
# @ Last Modified At: 2018-12-19 14:25:52
# @ Description: 微信游戏棍棍英雄的辅助.

import os
import cv2
import numpy as np
import time
import random

def get_screenshot():
    os.system('adb shell screencap -p /sdcard/screenshot.png')
    os.system('adb pull /sdcard/screenshot.png ./image/screenshot.png')

def press(distance):
    if distance<660:
        press_time=int(distance*1.33)#填入相关系数
    elif distance>= 660 and distance<800:
        press_time=int(distance*1.3)
    elif distance>780:
        press_time=int(distance*1.26)
    rand = random.randint(0,9)*10
    press_cmd = ('adb shell input swipe %i %i %i %i '+str(press_time))\
        %(320+rand,410+rand, 320+rand,410+rand)
    os.system(press_cmd)
    print(press_cmd)

#准备开始的模板
img_start = cv2.imread('./image/start.png',0)
#准备小人的模板
img_man = cv2.imread('./image/man.png' , 0 )
w1,h1 = img_man.shape[::-1]
#结束画面的模板
img_end = cv2.imread('./image/end.png', 0 )

#开始程序
get_screenshot()
img_rgb=cv2.imread('./image/screenshot.png',0)
method = eval('cv2.TM_CCOEFF_NORMED')
res_end=cv2.matchTemplate(img_rgb,img_start, method )
if cv2.minMaxLoc(res_end)[1] > 0.95:
    os.system('adb shell input tap 550 1480')
    time.sleep(1)

#开始循环
for i in range (2000):
    get_screenshot()
    img_rgb=cv2.imread('./image/screenshot.png',0)

    #如果匹配到点击跳过就结束循环
    res_end=cv2.matchTemplate(img_rgb,img_end, method )
    if cv2.minMaxLoc(res_end)[1] > 0.9:
        print('Game over!')
        #os.system('adb shell input tap 550 1480')
        #time.sleep(1)
        #os.system('adb shell input tap 550 1480')
        #time.sleep(3)
        break

    #匹配模板中的小人位置
    res1=cv2.matchTemplate(img_rgb,img_man, method)
    min_val1,max_val1,min_loc1,max_loc1=cv2.minMaxLoc(res1)
    #center1_loc= (max_loc1[0]+109,1380)
    for weight_ren in range(max_loc1[0]+50,272):
        if img_rgb[1390,weight_ren] !=161 :
            center1_loc=(weight_ren-1,1380)
            break


    flag = 0
    for weight in range(135,1080):
        if img_rgb[1390,weight]==60 and flag == 0:
            flag=1
            left=weight
        elif img_rgb[1390,weight]==60 and flag==1:
            right=weight
    center = (right-left)//2+left
    center2_loc=(center,1380)
    #print(center2_loc)#输出中心点的位置
    for j in range(1920):
        img_rgb[j,center]=255
        img_rgb[j,max_loc1[0]+109]=255
    cv2.imwrite('./image/result.png',img_rgb)
    distance=center2_loc[0]-center1_loc[0]
    print(distance)

    #按下屏幕
    press(distance)
    time.sleep(3)

